//
//  MainDetViewController.m
//  YaDiuDiu
//
//  Created by 欧洪飞 on 2017/10/15.
//  Copyright © 2017年 jy. All rights reserved.
//

#import "MainDetViewController.h"
#import "MainDetailHeadCell.h"
#import "MainDetailModel.h"
#import "NSString+Extension.h"
#import "MoodDetView.h"

#import "PayForViewController.h"
@interface MainDetViewController ()<UITableViewDelegate,UITableViewDataSource,UIWebViewDelegate>
{
    NSMutableArray *array;
    CGFloat _webViewHeight;

}
/*tableView*/
@property(nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSDictionary *dic;
@property(nonatomic,strong)MainDetailModel *mainModel;
@property(nonatomic,strong)UIWebView *webView;

@end

@implementation MainDetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setBGColor];
    [self showNav:@"商品详情"];
    array = [NSMutableArray array];
    [self loadData];
    [self loadUI];

}

-(MainDetailModel *)mainModel
{
    if (!_mainModel) {
        
        _mainModel = [[MainDetailModel alloc]init];
    }
    return _mainModel;
}

-(UIWebView *)webView
{
    if (!_webView) {
        
        _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 1)];
        _webView.delegate = self;
        _webView.backgroundColor = [UIColor redColor];
    }
    return _webView;
}

/*
  init tableView
 */
-(UITableView *)tableView
{
    if (!_tableView) {
        
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight - 50 - 64) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.hidden = YES;
    }
    return _tableView;
}

#pragma mark -- tableVIewDelegate,dataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
        
        MainDetailHeadCell *cell = [MainDetailHeadCell tableViewCellWithTableView:tableView];
        cell.model = self.mainModel;
        return cell;
    }else
    {
        static NSString *cellID = @"cellID";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (!cell) {
            
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell.contentView addSubview:self.webView];

        }
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
      
        NSString *str = [NSString stringWithFormat:@"%@",self.mainModel.subject];
        return ScreenWidth * 341 / 375 + 60 + [str sizeWithFont:[UIFont systemFontOfSize:16] maxW:ScreenWidth - 2*13].height+10;
    }else
    {
        return _webViewHeight;
        
    }
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        
        UIView *av = [[UIView alloc]init];
        av.backgroundColor = [UIColor whiteColor];
        
        //图标
        UIImageView *imgV = [[UIImageView alloc]init];
        imgV.image = [UIImage imageNamed:@"商品"];
        [av addSubview:imgV];
        [imgV mas_makeConstraints:^(MASConstraintMaker *make) {
        
            make.left.mas_offset(13);
            make.centerY.equalTo(av);
            make.width.height.mas_offset(17);
            
        }];
        //商品详情
        UILabel *titleLabel = [[UILabel alloc]init];
        titleLabel.text = @"商品详情";
        [av addSubview:titleLabel];
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.left.equalTo(imgV.right).offset(10);
            make.centerY.equalTo(av.centerY);
        }];
        return av;
    }
    return nil;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        
        return 44.f;
    }
    return 0.001f;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        
        return 15.f;
    }
    return 0.001f;
}

/*
 设置UI
 */
- (void)loadUI{
    
    [self.view addSubview:self.tableView];
    
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenHeight-50, ScreenWidth, 50)];
    [self.view addSubview:footView];
    
    //分割线
    UILabel *lab = [[UILabel alloc] init];
    lab.backgroundColor = COLOR_RGB(230, 230, 230, 1);
    [footView addSubview:lab];
    
    [lab makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(footView.left);
        make.top.equalTo(footView.top).offset(0);
        make.height.equalTo(1);
        make.right.equalTo(footView.right);
    }];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.backgroundColor = COLOR_RGB(253, 17, 66, 1);
    btn.frame = CGRectMake(ScreenWidth/3*2, 0, ScreenWidth/3, 50);
    [btn setTitle:@"立即抢购" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:18.0];
    [btn addTarget:self action:@selector(clickPay) forControlEvents:UIControlEventTouchUpInside];
    [footView addSubview:btn];

    if ([self.statue isEqualToString:@"2"]) {
        
        btn.hidden = NO;

    }else
    {
        btn.backgroundColor = [UIColor grayColor];
        btn.enabled = NO;
    }
    
    //秒杀价
    UILabel *lab1 = [[UILabel alloc] init];
    lab1.text = @"秒杀价";
    lab1.textColor = [UIColor redColor];
    lab1.font = [UIFont fontWithName:@"Arial-BoldItalicMT" size:17.0];
    [footView addSubview:lab1];
    [lab1 makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(footView.left).offset(16);
        make.top.equalTo(footView.top).offset(4);
    }];
    
    UILabel *lab1Price = [[UILabel alloc] init];
    lab1Price.text = [NSString stringWithFormat:@"￥%@",self.model.pprice];
    lab1Price.textColor = [UIColor redColor];
    [footView addSubview:lab1Price];
    [lab1Price makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(lab1.right).offset(8);
        make.centerY.equalTo(lab1.centerY);
    }];
    
    UILabel *lab2 = [[UILabel alloc] init];
    lab2.textColor = [UIColor darkGrayColor];
    lab2.text = @"原价";
    [footView addSubview:lab2];
    [lab2 makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(lab1.left);
        make.top.equalTo(lab1.bottom).offset(4);
    }];
    
    UILabel *lab2Price = [[UILabel alloc] init];
    lab2Price.textColor = [UIColor darkGrayColor];
    
    [footView addSubview:lab2Price];
    [lab2Price makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(lab2.right).offset(8);
        make.centerY.equalTo(lab2.centerY);
    }];
    
    //原价
    NSString * lab2PriceString = [NSString stringWithFormat:@"￥%@",self.model.oprice];
     NSMutableAttributedString * ma_price = [[NSMutableAttributedString alloc] initWithString:lab2PriceString];
     [ma_price addAttributes:@{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle], NSBaselineOffsetAttributeName : @(NSUnderlineStyleSingle)} range:NSMakeRange(0,lab2PriceString.length)];
    lab2Price.attributedText = ma_price;
}
#warning 此处是点击抢购按钮前往支付界面
/*
 立即抢购
 */
- (void)clickPay{
    if ([self.statue isEqualToString:@"2"]) {//支付
        NSLog(@"aaaa");
        PayForViewController *pay = [[PayForViewController alloc] init];
        
        NSLog(@"detail:%@",self.mainModel.subject);
        pay.price = self.model.pprice;
        pay.OrderName = @"aaaa";
        [self.navigationController pushViewController:pay animated:YES];
    }else
    {
//        btn.hidden = YES;
        [LICGToast showWithText:@"还未到商品秒杀时间"];
    }
    
    
}



/*
 详情数据
 */
- (void)loadData{
    
    [SVProgressHUD show];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    parmas[@"goods_id"] = self.model.id;
    
    NSString *url = [NSString stringWithFormat:@"%@/App/Seckill/goodsDetails",urlHead];
    [[AFHTTPSessionManager manager] POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"res:%@",responseObject);
        
        if ([responseObject[@"status"] integerValue ] == 200) {
        
            MainDetailModel *detailModel = [MainDetailModel mj_objectWithKeyValues:responseObject[@"content"]];
            self.mainModel = detailModel;
            
            [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",self.mainModel.detail]]]];
            [self.tableView reloadData];
        }
        
        

        [SVProgressHUD dismiss];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
        [SVProgressHUD dismiss];
    }];
    
}

#pragma mark - UIWebView Delegate Methods
-(void)webViewDidStartLoad:(UIWebView *)webView
{
    [SVProgressHUD showWithStatus:@"加载中..."];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    
    //自适应图片大小
    CGFloat width = [[UIScreen mainScreen]bounds].size.width - 20;
    
    NSString *jsStr = [NSString stringWithFormat:@"var script = document.createElement('script');"
                       "script.type = 'text/javascript';"
                       "script.text = \"function ResizeImages() { "
                       "var myimg,oldwidth;"
                       "var maxwidth = '%f';" //自定义宽度
                       "for(i=0;i <document.images.length;i++){"
                       "myimg = document.images[i];"
                       "if(myimg.width > maxwidth){"
                       "oldwidth = myimg.width;"
                       "myimg.width = maxwidth;"
                       "}"
                       "}"
                       "}\";"
                       "document.getElementsByTagName('head')[0].appendChild(script);",width];
    [_webView stringByEvaluatingJavaScriptFromString:jsStr];
    [_webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
    
    //字体大小
    [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '10px'"];
    
    
    webView.scrollView.scrollEnabled = NO;
    
    CGFloat webViewHeight =[[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"]floatValue];
    CGRect newFrame = webView.frame;
    newFrame.size.height= webViewHeight + 5;
    webView.frame= newFrame;
    //再次设置WebView高度（点）
    _webViewHeight = webView.frame.size.height + 10;
    
    _tableView.hidden = NO;
    [SVProgressHUD dismiss];
    [self.tableView reloadData];
    
}

-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [SVProgressHUD showErrorWithStatus:@"加载失败!"];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
